# 作者：要努力，努力，再努力
# 开发时间：2022/4/27 9:07

filename = 'student.txt'
import os


def main():
    while True:
        menu()
        selection = int(input('请选择菜单:'))
        if selection in [0, 1, 2, 3, 4, 5, 6, 7]:
            if selection == 1:
                insert()
            elif selection == 2:
                search()
            elif selection == 3:
                delete()
            elif selection == 4:
                modify()
            elif selection == 5:
                sort()
            elif selection == 6:
                total()
            elif selection == 7:
                show()
            elif selection == 0:
                confirm = input('您确定要退出系统？y/n')
                if confirm == 'y':
                    print('谢谢您的使用')
                    break
                else:
                    continue
            else:
                print('输入错误，请重新选择！')


def menu():
    print("================================学生信息管理系统================================")
    print('-----------------------------------功能菜单------------------------------------')
    print('\t\t\t\t\t1. 录入学生信息')
    print('\t\t\t\t\t2. 查找学生信息')
    print('\t\t\t\t\t3. 删除学生信息')
    print('\t\t\t\t\t4. 更新学生信息')
    print('\t\t\t\t\t5. 排序')
    print('\t\t\t\t\t6. 统计学生总人数')
    print('\t\t\t\t\t7. 显示学生信息')
    print('\t\t\t\t\t0. 退出系统')
    print('-----------------------------------------------------------------------------')


def insert():
    student_lst = []
    flag = True
    while True:
        try:
            id = int(input('请输入学生ID：'))
        except:
            print('输入的id格式不正确')
            flag = False
            break
        name = input('请输入学生姓名：')
        if not name:
            flag = False
            break
        try:
            english = int(input('请输入英文成绩'))
            python = int(input('请输入python成绩'))
            java = int(input('请输入java'))
        except:
            print('输入的成绩不是整数格式，请重新输入')
            continue
        student_lst.append({'id': id, 'name': name, 'english': english, 'python': python, 'java': java})
        answer = input('是否继续录入？y/n')
        if answer == 'y':
            continue
        else:
            flag = False
            break
    # 保存学生信息
    if flag:
        save(student_lst)
        print('录入信息成功！')


# 保存学生信息
def save(lst):
    print('save')
    try:
        stu_file = open(filename, 'a', encoding='utf-8')
    except:
        stu_file = open(filename, 'w', encoding='utf-8')
    for item in lst:
        stu_file.write(str(item) + '\n')
    stu_file.close()


def search():
    student_query = []
    while True:
        id = ''
        name = ''
        if os.path.exists(filename):
            mode = input('按ID查找输入1，按name输入2')
            if mode == '1':
                id = int(input('需要查找学生的ID：'))
            elif mode == '2':
                name = input('输入学生的姓名')
            else:
                print('输入错误，请重新输入')
                continue
            with open(filename, 'r', encoding='utf-8') as rfile:
                student_list = rfile.readlines()
            for item in student_list:
                d = dict(eval(item))
                if id != '':
                    if d['id'] == id:
                        student_query.append(d)
                elif name != '':
                    if d['name'] == name:
                        student_query.append(d)
            show_students(student_query)
            student_query.clear()
            answer = input('是否继续查询？y/n')
            if answer == 'y':
                continue
            else:
                break
        else:
            print('暂未有学生信息')
            break


def delete():
    while True:
        try:
            student_id = int(input('请输入学生id'))
        except:
            print('输入学生id错误，请重新输入！')
            continue
        if student_id != '':
            if os.path.exists(filename):
                # 输入id不为空之后，就去将文件当中的信息保存下来
                with open(filename, 'r', encoding='utf-8') as rfile:
                    student_oldlst = rfile.readlines()
            else:
                student_oldlst = []
            flag = False
            if student_oldlst:
                # 删除操作
                with open(filename, 'w', encoding='utf-8') as wfile:
                    d = {}
                    for item in student_oldlst:
                        d = dict(eval(item))
                        if d['id'] != student_id:
                            wfile.write(str(d) + '\n')
                        else:
                            flag = True
                    if flag:
                        print(f'学生{student_id}的信息已删除')
                    else:
                        print(f'没有找到学生{student_id}的学生信息')
            else:
                print('无学生信息')
                break
            show()
        answer = input('是否继续删除？y/n')
        if answer == 'y':
            continue
        else:
            break


def modify():
    show()
    while True:
        if os.path.exists(filename):
            with open(filename, 'r', encoding='utf-8') as rfile:
                student_old = rfile.readlines()
        else:
            print('无学生信息')
            break
        try:
            student_id = int(input('请输入学生id:'))
        except:
            print('输入格式有误，重新输入')
            continue
        with open(filename, 'w', encoding='utf-8') as wfile:
            for item in student_old:
                d = dict(eval(item))
                if d['id'] == student_id:
                    while True:
                        try:
                            d['name'] = input('学生姓名')
                            d['english'] = int(input('英语成绩'))
                            d['python'] = int(input('python成绩'))
                            d['java'] = int(input('java'))
                        except:
                            print('输入有误，重新输入')
                            continue
                        else:
                            break
                    wfile.write(str(d) + '\n')
                    print('修改成功')
                else:
                    wfile.write(str(d) + '\n')

        answer = input('是否继续修改？y/n')
        if answer == 'y':
            continue
        else:
            break


def sort():
    show()
    if os.path.exists(filename):
        with open(filename, 'r', encoding='utf-8') as rfile:
            student_list = rfile.readlines()

        # student_new 用来排序的列表
        student_new = []
        for item in student_list:
            d = dict(eval(item))
            student_new.append(d)

        # 0.升序 1.降序
        asc_or_dsc = int(input('请输入 0.升序 1.降序'))
        if asc_or_dsc == 0:
            asc_or_dsc_bool = False
        elif asc_or_dsc == 1:
            asc_or_dsc_bool = True
        else:
            print('输入有误，请重新输入')
            sort()

        # 按照什么方式排序
        mode = int(input('请选择排序方式（1.按英语成绩排序方式 2.按Python成绩排序方式 3. 按Java成绩排序方式 0.按总成绩排序方式）'))
        if mode == 1:
            student_new.sort(key=lambda x: int(x['english']), reverse=asc_or_dsc_bool)
        elif mode == 2:
            student_new.sort(key=lambda x: int(x['python']), reverse=asc_or_dsc_bool)
        elif mode == 3:
            student_new.sort(key=lambda x: int(x['java']), reverse=asc_or_dsc_bool)
        elif mode == 0:
            student_new.sort(key=lambda x: int(x['english']) + int(x['python']) + int(x['java']),
                             reverse=asc_or_dsc_bool)
        else:
            print('您的输入有误，请重新输入')
            sort()
        show_students(student_new)
    else:
        print('无学生信息')
        return


def total():
    if os.path.exists(filename):
        with open(filename, 'r', encoding='utf-8') as rfile:
            student_list = rfile.readlines()
        if student_list:
            print(f'一共有{len(student_list)}条学生信息')
        else:
            print('暂无学生信息')
    else:
        print('暂无学生信息')
        return


def show():
    student_list = []
    if os.path.exists(filename):
        with open(filename, 'r', encoding='utf-8') as rfile:
            list = rfile.readlines()
        for item in list:
            student_list.append(eval(item))
        if student_list:
            show_students(student_list)
    else:
        print('暂未保存数据')


def show_students(lst):
    if len(lst) == 0:
        print('没有学生信息')
    else:
        # 显示标题
        format_title = "{:^6}\t{:^12}\t{:^8}\t{:^10}\t{:^10}\t{:^8}\t"
        print(format_title.format('ID', '姓名', '英语成绩', 'python成绩', 'java成绩', '总成绩'))
        # 显示内容
        format_data = "{:^6}\t{:^12}\t{:^8}\t{:^10}\t{:^10}\t{:^8}\t"
        for item in lst:
            print(format_data.format(item.get('id'),
                                     item.get('name'),
                                     item.get('english'),
                                     item.get('python'),
                                     item.get('java'),
                                     int(item.get('english')) + item.get('python') + item.get('java')))


if __name__ == '__main__':
    main()
